package se.plingapp.controllerbeans;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import se.plingapp.entitybeans.Message;
import se.plingapp.enterprisebeans.MessageFacade;
import se.plingapp.entitybeans.User;
import se.plingapp.enterprisebeans.UserFacade;

/**
 * Message controller.
 *
 * @author Jens Björk
 */
@ManagedBean
@RequestScoped
public class MessageController {

    @EJB
    private MessageFacade messageFacade;
   
    private Message message = new Message();
    private List<Message> messageList = new ArrayList<Message>();

    public Message getMessage() {
        return this.message;
    }

    public Message getLatestMessage() {
        Message latestMsg = messageFacade.findByUser(this.getUser()).get(0);
        if (latestMsg == null) {
            return this.message;
        }
        return latestMsg;
    }

    public User getUser() {
        return (User)this.getBean("userController.user");
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public List<Message> getMessageList() {
        if(this.getUser() != null)
            return messageFacade.findByUser(this.getUser());
        else
            return messageFacade.findByUser(this.getActiveUser());
    }

    public String showEdit() {
        return "/user/dashboard.xhtml?faces-redirect=true";
    }

    public String doCreateMessage() {
        message.setUser(getActiveUser());
        message = messageFacade.create(message);
        return this.showEdit();
    }

    private User getActiveUser() {
        FacesContext fc = FacesContext.getCurrentInstance();
        User u = (User) fc.getExternalContext().getSessionMap().get("user");
        return u;
    }

    /**
     * Convenience method for evaluation Expression Language statements. Useful for calling other
     * controller beans, among other things.
     *
     * @param expr EL expression
     * @return 
     */
    private Object getBean(String expr){
        FacesContext context = FacesContext.getCurrentInstance();
        Application app = context.getApplication();
        ValueBinding binding = app.createValueBinding("#{" + expr + "}");
        return binding.getValue(context);
    }

}
